import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    showLoading: false,
    loginInfo: null,
    cartInfo: null,
    token: null
  },
  getters: {
    tokens(state) {
      return state.token || sessionStorage.getItem('token');
    },
    loginUser(state) {
      return state.loginInfo || JSON.parse(sessionStorage.getItem('loginInfo'));
    },
    cartList(state) {
      return state.cartInfo || JSON.parse(sessionStorage.getItem('cartInfo'));
    },
  },
  mutations: {
    changeLoading(state, payload) {
      state.showLoading = payload;
    },
    saveToken(state, payload) {
      state.token = payload;
      sessionStorage.setItem('token', payload);
    },
    saveLoginInfo(state, payload) {
      state.loginInfo = payload;
      sessionStorage.setItem('loginInfo', JSON.stringify(payload));
    },
    saveCartInfo(state, payload) {
      state.cartInfo = payload;
      sessionStorage.setItem('cartInfo', JSON.stringify(payload));
    },
    changeCartNum(state, { id, number }) {
      let c = this.getters.cartList;
      for (let i in c.valid) {
        if (c.valid[i].id == id) {
          c.valid[i].cart_num = number;
          break;
        }
      }
      state.cartInfo = c;
      sessionStorage.setItem('cartInfo', JSON.stringify(c));
    },
    loginOut(state) {
      state.token = null;
      state.loginInfo = null;
      state.cartInfo = null;
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('loginInfo');
      sessionStorage.removeItem('cartInfo');
    }
  },
  actions: {
    getCartInfo(context) {
      if (this.getters.tokens) {
        this._vm.$axios.get("/api/cart/list").then((d) => {
          console.log('cart_actions', d.data.data);
          if (d.data.status == 200) {
            context.commit("saveCartInfo", d.data.data);
          }
        });
      }
    }
  },
  modules: {
  }
})
